/**
 * @FileName: ThemesService.java
 * @Author
 * @Description:
 * @Date 2015年12月28日 下午3:26:32
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service;

import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Themes;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ResultCode;
import cn.hpclub.server.util.SystemConfigUtil;

public class ThemesService extends Service{
    static final int            TYPE_KAIHU = 1;
    public static ThemesService service    = new ThemesService();

    /**
     * 获取查询语句
     */
    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "from themes where 1=1";
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " order by sort asc,create_time desc";

        return sqlExceptSelect;
    }

    private String buildQuery(Entry<String, String> item){
        return " and " + item.getKey() + " like '%" + item.getValue() + "%'";
    }

    /**
     * @Title: delete
     * @Description:批量删除主题
     * @param ids主题ID
     * @return ResultCode
     */
    public ResultCode deleteThemes(String[] ids){
        return deleteRecords("themes", ids);
    }

    public String getSqlAuthorizationOrgExceptSelect(String themesId, ConcurrentHashMap<String, String> searchInfo){
        String orgFilter = InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true);
        String sqlExceptSelect = "FROM themes, organization org, themes_organization themes_org WHERE themes_org.org_id = org.id AND themes.id = themes_org.themes_id AND themes.id="
                + themesId + " AND org.id IN " + orgFilter;

        for(Entry<String, String> item : searchInfo.entrySet()){
            if(item.getKey() == "keywordOrg"){
                sqlExceptSelect += " AND (org.DisplayName LIKE '%" + item.getValue() + "%'";
                sqlExceptSelect += " OR org.NumCode LIKE '%" + item.getValue() + "%') ";
            }
        }
        sqlExceptSelect += " ORDER BY updated_time DESC";
        return sqlExceptSelect;
    }

    public String getSqlAuthorizationCityExceptSelect(String themesId, ConcurrentHashMap<String, String> searchInfo){
        // 查当前账号级别和下一级子节点，结合下面的" AND org.id=org.CityCode
        // "过滤出可看见和可配置的地市。如，全省账号，得到21个地市的数据；如成都账号，只能得到成都市;地市以下的账号，看不到任何数据
        String orgFilter = InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), 1, true);
        String sqlExceptSelect = " FROM themes,organization org,themes_city WHERE themes.id= themes_city.themes_id AND themes_city.city_org_id = org.id AND themes.id="
                + themesId + " AND org.id IN " + orgFilter; // + " AND
                                                            // org.id=org.CityCode
                                                            // "

        for(Entry<String, String> item : searchInfo.entrySet()){
            if(item.getKey() == "keywordCity"){
                sqlExceptSelect += " AND (org.DisplayName LIKE '%" + item.getValue() + "%'";
                sqlExceptSelect += " OR org.NumCode LIKE '%" + item.getValue() + "%') ";
            }
        }
        sqlExceptSelect += " ORDER BY updated_time DESC";
        // System.out.println("sql:" + sqlExceptSelect);
        return sqlExceptSelect;
    }

    public String getSqlAuthorizationMemberExceptSelect(String themesId, ConcurrentHashMap<String, String> searchInfo){
        String orgFilter = InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), Constant.MAX_ORG_LEVEL, true);
        String sqlExceptSelect = "FROM themes_member, member_org WHERE themes_member.member_id = member_org.id AND themes_member.themes_id="
                + themesId + " AND member_org.org_id IN " + orgFilter;
        for(Entry<String, String> item : searchInfo.entrySet()){
            if(item.getKey() == "keywordMember"){
                sqlExceptSelect += " AND (member_org.name LIKE '%" + item.getValue() + "%'";
                sqlExceptSelect += " OR member_org.emp_code LIKE '%" + item.getValue() + "%'"
                        + " OR member_org.mobile LIKE '%" + item.getValue() + "%') ";
            }
        }
        sqlExceptSelect += " ORDER BY updated_time DESC";
        return sqlExceptSelect;
    }

    /**
     * @Title: deleteAuthorizationOrg
     * @Description:删除机构授权
     * @param ids
     * @return ResultCode
     */
    public ResultCode deleteAuthorizationOrg(String[] ids){
        return deleteRecords("themes_organization", ids);
    }

    public ResultCode deleteAuthorizationCity(String[] ids){
        return deleteRecords("themes_city", ids);
    }

    public ResultCode deleteAllAuthorizationMember(String themesId){
        String sql = "delete from themes_member where themes_id=?";
        int result = Db.update(sql, themesId);
        System.out.println(result);
        if(result>0){
            return ResultCode.SUCCESS;
        }else{
            return ResultCode.FAILED;
        }
    }

    /**
     * @Title: deleteRecords
     * @Description:批量删除数据
     * @param tableName
     * @param ids
     * @return ResultCode
     */
    private ResultCode deleteRecords(String tableName, String[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("delete from " + tableName + " where id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return ResultCode.PARAM_ERROR;
        }
        boolean result = Themes.dao.update(sb.toString(), ids);
        if(result){
            return ResultCode.SUCCESS;
        } else{
            return ResultCode.FAILED;
        }
    }

    /**
     * @Title: deleteAuthorizationMember
     * @Description:删除人员授权
     * @param ids
     * @return ResultCode
     */
    public ResultCode deleteAuthorizationMember(String[] ids){
        return deleteRecords("themes_member", ids);
    }

    /**
     * @Title: getAuthedThemes
     * @Description:TODO
     * @param orgId
     * @param userId
     *            TODO
     * @return JSONArray
     */

    public JSONArray getAuthedThemes(int orgId, int userId){

        // select themes.*,org.WebsiteId,org.WebsiteCode,org.CityCode from
        // themes,(select orgcls.WebsiteId as WebsiteCode,org.WebsiteId as
        // WebsiteId,org.CityCode from organization org,organization_class
        // orgcls where org.id=54835 and org.WebsiteId=orgcls.id)org where (
        // (type!=5 and enabled =1 and id in(select module_id from
        // organization_class_map where organization_class_map.class_id =
        // org.WebsiteId and organization_class_map.org_id=org.CityCode)) or
        // (type=5 and enabled=1 and (org.WebsiteCode LIKE '6%' OR
        // org.WebsiteCode = '1000' OR org.WebsiteCode = '4800') ) ) order by
        // sort asc;
        // AB+A非C的逻辑。type！=5,按照前端配置。type=5按照网店类型是否是客户经理，
        int topOrgId = InterfaceUtil.getIdTop();
        String sql = "SELECT themes.*, org.WebsiteId, org.WebsiteCode, org.CityCode FROM themes, ( SELECT org.id AS org_id, orgcls.WebsiteId AS WebsiteCode, org.WebsiteId AS WebsiteId, org.CityCode FROM organization org, organization_class orgcls WHERE org.id = ? AND org.WebsiteId = orgcls.id ) org WHERE (( type != 5 AND enabled = 1 AND id IN ( SELECT module_id FROM organization_class_map WHERE organization_class_map.class_id = org.WebsiteId AND organization_class_map.org_id = org.CityCode )) OR ( type = 5 AND enabled = 1 AND ( org.WebsiteCode LIKE '6%' OR org.WebsiteCode = '1000' OR org.WebsiteCode = '4800' OR org_id IN ( SELECT id FROM organization WHERE ( parentid = ? OR parentid IN ( SELECT id FROM organization WHERE parentid = ? ))))) OR ( enabled = 1 AND id IN ( SELECT themes_organization.themes_id FROM themes_organization WHERE org_id = ? )) OR ( enabled = 1 AND id IN ( SELECT themes_member.themes_id FROM themes_member WHERE member_id = ? )) "
                + "OR ( enabled = 1 AND id IN ( SELECT themes_city.themes_id FROM themes_city WHERE city_org_id = "
                + InterfaceUtil.getCitySql(String.valueOf(orgId), "id") + " ))" + ") ORDER BY sort ASC;";

        List<Record> records = Db.find(sql, orgId, topOrgId, topOrgId, orgId, userId);

        JSONArray array = new JSONArray();
        for(Record theme : records){
            JSONObject obj = new JSONObject();
            obj.put(ClientApiConstant.Key.THEME_MODULE_ID, theme.getInt(Themes.ID));
            String name = theme.getStr(Themes.NAME);
            obj.put(ClientApiConstant.Key.THEME_NAME, name == null ? "" : name);
            String imgUrl = SystemConfigUtil.getSystemConfig().getHostPrefix() + theme.getStr(Themes.IMG_URL);
            obj.put(ClientApiConstant.Key.IMG_URL, imgUrl == null ? "" : imgUrl);

            Integer type = theme.getInt("type");
            obj.put(ClientApiConstant.Key.TYPE, type);

            String linkUrl = theme.getStr(Themes.LINK_URL);
            linkUrl = (linkUrl == null ? "" : linkUrl);
            obj.put(ClientApiConstant.Key.LINK_URL, getLinkUrl(orgId, type, linkUrl));

            obj.put(ClientApiConstant.Key.SORT, theme.getInt("sort"));

            obj.put(ClientApiConstant.Key.IS_USABLE, 1);
            String desc = theme.getStr(Themes.DESC);
            obj.put(ClientApiConstant.Key.REMARK, desc == null ? "" : desc);

            obj.put(ClientApiConstant.Key.LINK_TYPE, 0);
            obj.put(ClientApiConstant.Key.APPID, ClientApiConstant.APPKEY_DZG_VALUE);
            obj.put(ClientApiConstant.Key.STORE_MODULE_ID, orgId);

            array.put(obj);
        }
        return array;
    }

    /**
     * @Title: 构造linkUrl
     * @Description: 对于type为开户的主题，通过linkurl来指示客户端该呈现选号入网和实名开卡还是只显示实名开卡。
     *               1)目前，针对成都及以下的机构，返回选号入网,实名开卡。成都以外的，仅返回实名开卡。
     *               2）当需求变成所有账号都返回选号入网，实名开卡时，额可以修改该方法，也可直接修改themes,开户对应的linkur为
     *               “选号入网,实名开卡” 客户端收到实名开卡，则仅提供实名开卡功能，反之，提供选号入网和实名开卡功能。
     * @param orgId
     * @param type
     * @param defaultLinkUrl
     * @return String
     */
    public String getLinkUrl(int orgId, int type, String defaultLinkUrl){
        // 开户主题，根据用户地市，返回不同的linkurl值，客户端根据linkurl确定是否显示选号入网和营销活动
        if(type == TYPE_KAIHU){
            if(InterfaceUtil.isOrgInChengDu(orgId)){
                // 成都
                return "选号入网,营销活动选号入网,实名开卡";

            } else if(InterfaceUtil.isOrgInHotCity(orgId)){
                // 绵阳、德阳、眉山
                return "选号入网,实名开卡";
            } else{
                // 其他地市，来自配置,目前默认只有实名开卡
                return defaultLinkUrl;

            }
        }

        // 其他主题，配置什么就返回什么
        return defaultLinkUrl;
    }
}
